#include<iostream>
#include<cstdlib>
#include<unistd.h>

using namespace std;

//获得参数
bool GetQueryString(std::string&query_string)
{
    bool result = false;
    std::string method = getenv("METHOD");
    if(method == "GET")
    {
        query_string = getenv("QUERY_STRING");
        result = true;
        // cerr<<"Debug QUERY_STRING:"<<query_string<<endl;
    }
    else if (method == "POST")
    {
        // cerr<<"content-length:"<<getenv("CONTENT_LENGTH")<<endl;
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char c =0;
        while (content_length)
        {
            read(0,&c,1);
            query_string.push_back(c);
            content_length--;
        } 
        result= true; 
        // cerr<<"Debug POST CONTENT_LENGTH:"<<query_string<<endl;
    }
    else
    {
        result = false;
    }
    return result ;
}

void CutString(std::string &in , const std::string &sep,std::string &out1,std::string &out2)
{
    auto pos = in.find(sep);
    if(std::string::npos != pos)
    {
        out1 = in.substr(0,pos);
        out2 = in.substr(pos+sep.size());
    }
}

int main()
{
    std::string query_string;
    GetQueryString(query_string);
    std::cerr<<"get query_string success"<<std::endl;
    //处理请求，返回给http，a=1999&b=2024 -> a=1999,b=2024
    std::string str1;
    std::string str2;
    CutString(query_string,"&",str1,str2);

    std::string name1;
    std::string value1;
    CutString(str1,"=",name1,value1);

    std::string name2;
    std::string value2;
    CutString(str2,"=",name2,value2);

    //文件描述符1输出
    std::cout<<name1<<": "<<value1 << std::endl;
    std::cout<<name2<<": "<<value2 << std::endl;

    std::cerr<<name1<<": "<<value1 << std::endl;
    std::cerr<<name2<<": "<<value2 << std::endl;

    int x = atoi(value1.c_str());
    int y = atoi(value2.c_str());

    std::cout<<"<html>";
    std::cout<<"<head><meta charset=\"utf-8\"></head>";
    std::cout<<"<body>";
    std::cout<<"<h3>"<<value1<<"+"<<value2<<" = "<<x+y<<"</h3>";
    std::cout<<"<h3>"<<value1<<"-"<<value2<<" = "<<x-y<<"</h3>";
    std::cout<<"<h3>"<<value1<<"*"<<value2<<" = "<<x*y<<"</h3>";
    std::cout<<"<h3>"<<value1<<"/"<<value2<<" = "<<x/y<<"</h3>";
    std::cout<<"</body>";
    std::cout<<"</html>";
    
    // cerr<<"debug test :"<<getenv("METHOD")<<endl;
    return 0;
}
